<?php

namespace Trawind\Extension\Criteria;

use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Builder;
use Trawind\Basics\TrawindTransformer;
use Illuminate\Database\Eloquent\Model;
use Prettus\Repository\Contracts\CriteriaInterface;
use Prettus\Repository\Contracts\RepositoryInterface;
use Trawind\Basics\Exceptions\LogicException;


class CustomFieldRequestCriteria implements CriteriaInterface
{

    /**
     * @var TrawindTransformer $transformer
     */
    protected $transformer;


    public function __construct($transformer)
    {
        $this->transformer = $transformer;
    }


    /**
     * Apply criteria in query repository
     *
     * @param  Builder|Model        $model
     * @param  RepositoryInterface  $repository
     * @return mixed
     * @throws \Exception
     */
    public function apply($model, RepositoryInterface $repository)
    {
        $withKey = config('repository.criteria.params.with', 'with');
        $orderBy = config('repository.criteria.params.orderBy', 'orderBy');
        $sortedBy = config('repository.criteria.params.sortedBy', 'sortedBy');
        $withValue = request($withKey, '');

        is_null($businessType = $model->businessType) and LogicException::error(get_class($model).'#businessType is Undefined.');
        $customFields = $this->transformer::getInstance($businessType)->details;
        $withLocalBusinessType = array_filter(array_values($customFields['localBusinessType']));

        $newWithValue = array_unique(array_filter(array_merge(explode(';', $withValue), $withLocalBusinessType)));
        request()[$withKey] = join(';', $newWithValue);
        if (is_null(request()->input('orderBy')) && !is_null($customFields['sort_field']['sort_field'] ?? null)) {
            request()[$orderBy] = $customFields['sort_field']['sort_field']['name'];
            request()[$sortedBy] = $customFields['sort_field']['sort_is_asc'] ? 'asc' : 'desc';
        }

        return $model;
    }

}
